{% extends 'site/base.html' %}
{% load static %}

{% block title %}Checkout - PECCO{% endblock %}

{% block extra_css %}
<style>
/* Apple-inspired minimalist design */
.checkout-container {
  max-width: 1200px;
  margin: 100px auto 80px;
  padding: 0 24px;
  min-height: 400px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  font-size: 17px;
  color: #86868b;
  font-weight: 400;
}

/* Header Section */
.checkout-header {
  text-align: center;
  margin-bottom: 56px;
}

.checkout-header h1 {
  font-size: 48px;
  font-weight: 600;
  color: #1d1d1f;
  margin-bottom: 16px;
  letter-spacing: -0.5px;
}

/* Step Indicator - Apple Style */
.checkout-steps {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 32px;
  position: relative;
}

.checkout-steps::before {
  content: '';
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  width: 200px;
  height: 2px;
  background: #e5e5e7;
  z-index: 0;
}

.checkout-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: #86868b;
  position: relative;
  z-index: 1;
  transition: all 0.3s ease;
}

.checkout-step.active {
  color: #0F2A43;
}

.checkout-step.completed {
  color: #34c759;
}

.step-number {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #f5f5f7;
  color: #86868b;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 16px;
  border: 2px solid transparent;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.checkout-step.active .step-number {
  background: #0F2A43;
  color: white;
  border-color: #0F2A43;
  box-shadow: 0 4px 12px rgba(15, 42, 67, 0.2);
}

.checkout-step.completed .step-number {
  background: #34c759;
  color: white;
  border-color: #34c759;
}

.step-label {
  font-size: 13px;
  font-weight: 500;
  text-align: center;
  white-space: nowrap;
}

/* Main Content Layout */
.checkout-content {
  display: grid;
  grid-template-columns: 1fr 420px;
  gap: 48px;
  margin-top: 48px;
}

.checkout-main {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.checkout-section {
  background: #ffffff;
  border-radius: 18px;
  padding: 32px;
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(0, 0, 0, 0.04);
  transition: box-shadow 0.3s ease;
}

.checkout-section:hover {
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f5f5f7;
}

.section-title {
  font-size: 22px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0;
  letter-spacing: -0.3px;
}

.section-action {
  color: #0066cc;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 15px;
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 10px;
  transition: all 0.2s ease;
}

.section-action:hover {
  background: rgba(0, 102, 204, 0.08);
  color: #0055b3;
}

/* Address Selection - Compact Single Line Design */
.address-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.address-card {
  border: 2px solid #e5e5e7;
  border-radius: 12px;
  padding: 16px 20px;
  cursor: pointer;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  background: #fafafa;
  display: flex;
  align-items: center;
  gap: 16px;
}

.address-card:hover {
  border-color: #0F2A43;
  background: #ffffff;
  transform: translateY(-1px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.address-card.selected {
  border-color: #0F2A43;
  background: #ffffff;
  box-shadow: 0 4px 20px rgba(15, 42, 67, 0.12);
}

.address-card.selected::before {
  content: '✓';
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  width: 24px;
  height: 24px;
  background: #34c759;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 700;
  box-shadow: 0 2px 8px rgba(52, 199, 89, 0.3);
}

.address-card .default-badge {
  position: absolute;
  top: -8px;
  right: 16px;
  background: linear-gradient(135deg, #0F2A43 0%, #1a4d7a 100%);
  color: white;
  padding: 4px 10px;
  border-radius: 8px;
  font-size: 11px;
  font-weight: 600;
  letter-spacing: 0.3px;
  text-transform: uppercase;
  box-shadow: 0 2px 8px rgba(15, 42, 67, 0.2);
}

.address-content {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  padding-right: 40px;
}

.address-name {
  font-size: 15px;
  font-weight: 600;
  color: #1d1d1f;
  white-space: nowrap;
  min-width: 140px;
}

.address-details {
  color: #86868b;
  font-size: 14px;
  line-height: 1.4;
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.address-details span {
  display: inline;
}

.address-details .separator {
  color: #d2d2d7;
  margin: 0 4px;
}

.address-phone {
  color: #86868b;
  font-size: 14px;
  white-space: nowrap;
}

/* No Address State */
.no-address {
  text-align: center;
  padding: 48px 24px;
  color: #86868b;
}

.no-address p {
  margin-bottom: 20px;
  font-size: 15px;
}

/* Order Items Preview */
.cart-items-preview {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.cart-item-preview {
  display: flex;
  gap: 16px;
  align-items: center;
  padding: 12px;
  background: #fafafa;
  border-radius: 12px;
  transition: background 0.2s ease;
}

.cart-item-preview:hover {
  background: #f5f5f7;
}

.cart-item-image {
  width: 72px;
  height: 72px;
  object-fit: cover;
  border-radius: 10px;
  border: 1px solid rgba(0, 0, 0, 0.06);
}

.cart-item-info {
  flex: 1;
}

.cart-item-name {
  font-size: 15px;
  font-weight: 600;
  color: #1d1d1f;
  margin-bottom: 4px;
  letter-spacing: -0.2px;
}

.cart-item-variant {
  font-size: 13px;
  color: #86868b;
  margin-bottom: 8px;
}

.cart-item-price-qty {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.cart-item-price {
  font-size: 15px;
  color: #0F2A43;
  font-weight: 600;
}

.cart-item-qty {
  font-size: 13px;
  color: #86868b;
  background: #ffffff;
  padding: 4px 12px;
  border-radius: 8px;
  border: 1px solid #e5e5e7;
}

/* Order Summary Sidebar - Apple Style */
.checkout-summary {
  background: #ffffff;
  border-radius: 18px;
  padding: 32px;
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(0, 0, 0, 0.04);
  position: sticky;
  top: 120px;
  height: fit-content;
}

.summary-title {
  font-size: 22px;
  font-weight: 600;
  color: #1d1d1f;
  margin-bottom: 24px;
  letter-spacing: -0.3px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f5f5f7;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 0;
  font-size: 15px;
  color: #1d1d1f;
}

.summary-row span:first-child {
  color: #86868b;
  font-weight: 400;
}

.summary-row .amount {
  font-weight: 600;
  color: #1d1d1f;
}

.summary-row.total {
  border-top: 1px solid #e5e5e7;
  margin-top: 16px;
  padding-top: 20px;
  font-size: 20px;
  font-weight: 600;
}

.summary-row.total span:first-child {
  color: #1d1d1f;
  font-weight: 600;
}

.summary-row.total .amount {
  color: #0F2A43;
  font-size: 24px;
}

.summary-shipping-note {
  font-size: 13px;
  color: #34c759;
  text-align: center;
  padding: 12px 16px;
  margin: 16px 0;
  background: rgba(52, 199, 89, 0.08);
  border-radius: 10px;
  font-weight: 500;
  border: 1px solid rgba(52, 199, 89, 0.15);
}

/* Order Note - Apple Style Textarea */
.order-note {
  margin-top: 24px;
  margin-bottom: 24px;
}

.order-note label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #1d1d1f;
  margin-bottom: 10px;
  letter-spacing: -0.1px;
}

.order-note textarea {
  width: 100%;
  padding: 14px 16px;
  border: 1.5px solid #d2d2d7;
  border-radius: 12px;
  font-size: 15px;
  resize: vertical;
  min-height: 88px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
  color: #1d1d1f;
  background: #fafafa;
  transition: all 0.2s ease;
  line-height: 1.5;
  box-sizing: border-box; /* 确保 padding 不会导致元素超出容器 */
}

.order-note textarea::placeholder {
  color: #86868b;
}

.order-note textarea:hover {
  border-color: #b8b8bb;
  background: #ffffff;
}

.order-note textarea:focus {
  outline: none;
  border-color: #0F2A43;
  background: #ffffff;
  box-shadow: 0 0 0 4px rgba(15, 42, 67, 0.08);
}

/* Place Order Button - Apple Style */
.place-order-btn {
  width: 100%;
  padding: 16px 24px;
  background: linear-gradient(135deg, #0F2A43 0%, #1a4d7a 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 17px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  margin-top: 8px;
  letter-spacing: -0.2px;
  box-shadow: 0 4px 16px rgba(15, 42, 67, 0.2);
}

.place-order-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #0d2338 0%, #153d63 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(15, 42, 67, 0.3);
}

.place-order-btn:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(15, 42, 67, 0.2);
}

.place-order-btn:disabled {
  background: #d2d2d7;
  cursor: not-allowed;
  box-shadow: none;
  color: #86868b;
}

/* Responsive Design */
@media (max-width: 968px) {
  .checkout-content {
    grid-template-columns: 1fr;
    gap: 32px;
  }

  .checkout-summary {
    position: static;
  }

  .checkout-header h1 {
    font-size: 40px;
  }

  .checkout-steps::before {
    width: 160px;
  }
}

@media (max-width: 640px) {
  .checkout-container {
    margin: 80px auto 60px;
    padding: 0 16px;
  }

  .checkout-header h1 {
    font-size: 32px;
  }

  .checkout-section {
    padding: 24px 20px;
  }

  .address-card {
    flex-direction: column;
    align-items: flex-start;
    padding: 16px;
  }

  .address-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    padding-right: 0;
  }

  .address-name {
    min-width: auto;
  }

  .checkout-steps {
    gap: 12px;
  }

  .checkout-steps::before {
    width: 120px;
  }

  .step-label {
    font-size: 12px;
  }

  .step-number {
    width: 36px;
    height: 36px;
    font-size: 14px;
  }
}

/* Order Success Modal - Apple Style */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
}

.modal-overlay.show {
  opacity: 1;
  visibility: visible;
}

.modal-content {
  background: white;
  border-radius: 20px;
  padding: 48px 40px;
  max-width: 480px;
  width: 90%;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  position: relative;
  transform: scale(0.9) translateY(20px);
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.modal-overlay.show .modal-content {
  transform: scale(1) translateY(0);
}

.modal-close {
  position: absolute;
  top: 16px;
  right: 16px;
  width: 32px;
  height: 32px;
  border: none;
  background: #f5f5f7;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #86868b;
  transition: all 0.2s ease;
}

.modal-close:hover {
  background: #e5e5e7;
  color: #1d1d1f;
  transform: rotate(90deg);
}

.modal-icon {
  width: 80px;
  height: 80px;
  margin: 0 auto 24px;
  background: linear-gradient(135deg, #34c759 0%, #30d158 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: successPulse 0.6s ease;
}

@keyframes successPulse {
  0% {
    transform: scale(0);
    opacity: 0;
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.modal-icon svg {
  width: 48px;
  height: 48px;
  stroke: white;
  stroke-width: 3;
  stroke-linecap: round;
  stroke-linejoin: round;
  fill: none;
  stroke-dasharray: 100;
  stroke-dashoffset: 100;
  animation: checkmark 0.6s ease 0.3s forwards;
}

@keyframes checkmark {
  to {
    stroke-dashoffset: 0;
  }
}

.modal-title {
  font-size: 28px;
  font-weight: 600;
  color: #1d1d1f;
  text-align: center;
  margin-bottom: 12px;
  letter-spacing: -0.5px;
}

.modal-message {
  font-size: 15px;
  color: #86868b;
  text-align: center;
  line-height: 1.6;
  margin-bottom: 8px;
}

.modal-order-number {
  font-size: 17px;
  font-weight: 600;
  color: #0F2A43;
  text-align: center;
  margin-bottom: 32px;
  padding: 12px 20px;
  background: #f5f5f7;
  border-radius: 10px;
  font-family: 'SF Mono', 'Monaco', 'Courier New', monospace;
}

.modal-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.modal-btn {
  padding: 14px 24px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;
  text-align: center;
  text-decoration: none;
  display: block;
}

.modal-btn-primary {
  background: linear-gradient(135deg, #0F2A43 0%, #1a4d7a 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(15, 42, 67, 0.3);
}

.modal-btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(15, 42, 67, 0.4);
}

.modal-btn-primary:active {
  transform: translateY(0);
}

.modal-btn-secondary {
  background: #f5f5f7;
  color: #1d1d1f;
}

.modal-btn-secondary:hover {
  background: #e5e5e7;
}

@media (max-width: 640px) {
  .modal-content {
    padding: 36px 24px;
  }

  .modal-title {
    font-size: 24px;
  }

  .modal-order-number {
    font-size: 15px;
  }
}
</style>
{% endblock %}

{% block content %}
<div class="checkout-container" id="checkout-container">
  <div class="loading-container" id="loading-container">
    Loading checkout...
  </div>
</div>

<!-- Order Success Modal -->
<div class="modal-overlay" id="success-modal">
  <div class="modal-content">
    <button class="modal-close" onclick="closeSuccessModal()">×</button>

    <div class="modal-icon">
      <svg viewBox="0 0 52 52">
        <path d="M14 27l8 8 16-16"/>
      </svg>
    </div>

    <h2 class="modal-title">Order Placed Successfully!</h2>
    <p class="modal-message">Thank you for your purchase. Your order has been confirmed.</p>
    <div class="modal-order-number" id="modal-order-number"></div>

    <div class="modal-buttons">
      <button class="modal-btn modal-btn-primary" onclick="viewOrderHistory()">View Order History</button>
      <button class="modal-btn modal-btn-secondary" onclick="closeSuccessModal()">Continue Shopping</button>
    </div>
  </div>
</div>

<script>
// Use global variables from user-auth.js instead of declaring new ones
// const API_BASE is already defined globally
// authToken is already defined globally
// cart is already defined globally
let addresses = [];
let selectedAddressId = null;

async function loadCheckoutData() {
  // 检查登录状态
  if (!authToken) {
    window.location.href = '/';
    return;
  }

  try {
    // 加载购物车
    const cartResponse = await fetch(`${API_BASE}/cart/`, {
      headers: { 'Authorization': `Bearer ${authToken}` }
    });
    
    if (!cartResponse.ok) {
      throw new Error('Failed to load cart');
    }
    
    cart = await cartResponse.json();
    
    if (!cart.items || cart.items.length === 0) {
      alert('Your cart is empty');
      window.location.href = '/';
      return;
    }

    // 加载地址
    const addressResponse = await fetch(`${API_BASE}/users/addresses/`, {
      headers: { 'Authorization': `Bearer ${authToken}` }
    });
    
    if (addressResponse.ok) {
      addresses = await addressResponse.json();
      selectedAddressId = addresses.find(a => a.is_default)?.id || addresses[0]?.id;
    }

    // 渲染页面
    renderCheckoutPage();
  } catch (error) {
    console.error('Error loading checkout data:', error);
    alert('Failed to load checkout page');
    window.location.href = '/';
  }
}

// 重新加载地址列表（用于新增地址后刷新）
async function reloadAddresses() {
  try {
    const addressResponse = await fetch(`${API_BASE}/users/addresses/`, {
      headers: { 'Authorization': `Bearer ${authToken}` }
    });

    if (addressResponse.ok) {
      addresses = await addressResponse.json();

      // 如果之前没有选中的地址，选择默认地址或第一个地址
      if (!selectedAddressId && addresses.length > 0) {
        selectedAddressId = addresses.find(a => a.is_default)?.id || addresses[0]?.id;
      }

      // 重新渲染页面
      renderCheckoutPage();
    }
  } catch (error) {
    console.error('Error reloading addresses:', error);
  }
}

// 将 reloadAddresses 函数暴露到全局，以便 user-auth.js 可以调用
window.reloadCheckoutAddresses = reloadAddresses;

function renderCheckoutPage() {
  const container = document.getElementById('checkout-container');
  
  const subtotal = parseFloat(cart.total_price || 0);
  const FREE_SHIPPING_THRESHOLD = 100;
  const STANDARD_SHIPPING = 10;
  const shippingCost = subtotal >= FREE_SHIPPING_THRESHOLD ? 0 : STANDARD_SHIPPING;
  const total = subtotal + shippingCost;

  container.innerHTML = `
    <div class="checkout-header">
      <h1>Checkout</h1>
      <div class="checkout-steps">
        <div class="checkout-step active">
          <div class="step-number">1</div>
          <span class="step-label">Shipping Address</span>
        </div>
        <div class="checkout-step">
          <div class="step-number">2</div>
          <span class="step-label">Review & Place Order</span>
        </div>
      </div>
    </div>

    <div class="checkout-content">
      <div class="checkout-main">
        <!-- Shipping Address Section -->
        <div class="checkout-section">
          <div class="section-header">
            <h2 class="section-title">Shipping Address</h2>
            <button class="section-action" onclick="showAddAddressForm()">+ Add New Address</button>
          </div>
          
          ${addresses.length > 0 ? `
            <div class="address-list" id="address-list">
              ${addresses.map(address => `
                <div class="address-card ${address.id === selectedAddressId ? 'selected' : ''}"
                     data-address-id="${address.id}"
                     onclick="selectAddress(${address.id})">
                  ${address.is_default ? '<div class="default-badge">Default</div>' : ''}
                  <div class="address-content">
                    <div class="address-name">${address.first_name} ${address.last_name}</div>
                    <div class="address-details">
                      <span>${address.address_line1}${address.address_line2 ? ', ' + address.address_line2 : ''}</span>
                      <span class="separator">•</span>
                      <span>${address.city}, ${address.state} ${address.postal_code}</span>
                      <span class="separator">•</span>
                      <span>${address.country}</span>
                      ${address.phone ? `<span class="separator">•</span><span class="address-phone">📞 ${address.phone}</span>` : ''}
                    </div>
                  </div>
                </div>
              `).join('')}
            </div>
          ` : `
            <div class="no-address">
              <p>You don't have any saved addresses yet.</p>
              <button class="btn btn-primary" onclick="showAddAddressForm()">Add Shipping Address</button>
            </div>
          `}
        </div>

        <!-- Order Items Section -->
        <div class="checkout-section">
          <div class="section-header">
            <h2 class="section-title">Order Items (${cart.items.length})</h2>
          </div>
          
          <div class="cart-items-preview">
            ${cart.items.map(item => `
              <div class="cart-item-preview">
                <img src="${item.product_image || '/static/images/placeholder.png'}" alt="${item.product_name}" class="cart-item-image">
                <div class="cart-item-info">
                  <div class="cart-item-name">${item.product_name}</div>
                  <div class="cart-item-variant">${item.variant_name}</div>
                  <div class="cart-item-price-qty">
                    <span class="cart-item-price">€${parseFloat(item.price).toFixed(2)}</span>
                    <span class="cart-item-qty">Qty: ${item.quantity}</span>
                  </div>
                </div>
              </div>
            `).join('')}
          </div>
        </div>
      </div>

      <!-- Order Summary Sidebar -->
      <div class="checkout-summary">
        <h3 class="summary-title">Order Summary</h3>
        
        <div class="summary-row">
          <span>Subtotal (${cart.items.length} items)</span>
          <span class="amount">€${subtotal.toFixed(2)}</span>
        </div>
        
        <div class="summary-row">
          <span>Shipping</span>
          <span class="amount">
            ${shippingCost === 0 ? '<span style="color: #34c759; font-weight: 600;">FREE</span>' : `€${shippingCost.toFixed(2)}`}
          </span>
        </div>

        ${shippingCost === 0 ? `
          <div class="summary-shipping-note">
            🎉 You got free shipping!
          </div>
        ` : `
          <div class="summary-shipping-note" style="color: #86868b; background: rgba(134, 134, 139, 0.08); border-color: rgba(134, 134, 139, 0.15);">
            💡 Add €${(FREE_SHIPPING_THRESHOLD - subtotal).toFixed(2)} more for free shipping
          </div>
        `}
        
        <div class="summary-row total">
          <span>Total</span>
          <span class="amount">€${total.toFixed(2)}</span>
        </div>

        <div class="order-note">
          <label for="customer-note">Order Note (Optional)</label>
          <textarea id="customer-note" placeholder="Add any special instructions for your order..."></textarea>
        </div>
        
        <button class="place-order-btn" id="place-order-btn" onclick="placeOrder()" ${addresses.length === 0 ? 'disabled' : ''}>
          Place Order
        </button>
      </div>
    </div>
  `;
}

function selectAddress(addressId) {
  selectedAddressId = addressId;
  
  // 更新UI
  document.querySelectorAll('.address-card').forEach(card => {
    card.classList.remove('selected');
  });
  
  const selectedCard = document.querySelector(`[data-address-id="${addressId}"]`);
  if (selectedCard) {
    selectedCard.classList.add('selected');
  }
  
  // 启用下单按钮
  document.getElementById('place-order-btn').disabled = false;
}

// Modal functions
function showSuccessModal(orderNumber) {
  const modal = document.getElementById('success-modal');
  const orderNumberElement = document.getElementById('modal-order-number');
  orderNumberElement.textContent = `Order #${orderNumber}`;

  // Show modal with animation
  modal.style.display = 'flex';
  setTimeout(() => {
    modal.classList.add('show');
  }, 10);

  // Clear cart after successful order
  cart = { items: [], total_price: 0 };
  if (window.updateCartCount) {
    window.updateCartCount();
  }
}

function closeSuccessModal() {
  const modal = document.getElementById('success-modal');
  modal.classList.remove('show');
  setTimeout(() => {
    modal.style.display = 'none';
    // Redirect to home page
    window.location.href = '/';
  }, 300);
}

function viewOrderHistory() {
  // Close success modal first
  const successModal = document.getElementById('success-modal');
  successModal.classList.remove('show');
  setTimeout(() => {
    successModal.style.display = 'none';
  }, 300);

  // Redirect to home page and open account modal with orders tab
  window.location.href = '/?openAccount=orders';
}

// Error modal functions
function showErrorModal(message) {
  // Create error modal if it doesn't exist
  let modal = document.getElementById('error-modal');
  if (!modal) {
    modal = document.createElement('div');
    modal.id = 'error-modal';
    modal.className = 'modal';
    modal.innerHTML = `
      <div class="modal-content" style="max-width: 500px; text-align: center; padding: 40px;">
        <div style="width: 64px; height: 64px; background: #ff3b30; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 24px;">
          <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">
            <circle cx="12" cy="12" r="10"></circle>
            <line x1="15" y1="9" x2="9" y2="15"></line>
            <line x1="9" y1="9" x2="15" y2="15"></line>
          </svg>
        </div>
        <h2 style="font-size: 24px; font-weight: 600; margin-bottom: 16px; color: #1d1d1f;">Order Failed</h2>
        <p id="error-modal-message" style="font-size: 16px; color: #6e6e73; margin-bottom: 32px; white-space: pre-line; line-height: 1.6;"></p>
        <button onclick="closeErrorModal()" class="btn-primary" style="width: 100%; padding: 14px;">OK</button>
      </div>
    `;
    document.body.appendChild(modal);
  }

  // Set message and show modal
  document.getElementById('error-modal-message').textContent = message;
  modal.style.display = 'flex';
  setTimeout(() => {
    modal.classList.add('show');
  }, 10);
}

function closeErrorModal() {
  const modal = document.getElementById('error-modal');
  if (modal) {
    modal.classList.remove('show');
    setTimeout(() => {
      modal.style.display = 'none';
    }, 300);
  }
}

// Close modal when clicking on overlay
document.addEventListener('DOMContentLoaded', () => {
  const successModal = document.getElementById('success-modal');
  if (successModal) {
    successModal.addEventListener('click', (e) => {
      if (e.target === successModal) {
        closeSuccessModal();
      }
    });
  }

  // Add event listener for error modal
  document.addEventListener('click', (e) => {
    const errorModal = document.getElementById('error-modal');
    if (errorModal && e.target === errorModal) {
      closeErrorModal();
    }
  });
});

async function placeOrder() {
  if (!selectedAddressId) {
    alert('Please select a shipping address');
    return;
  }

  const btn = document.getElementById('place-order-btn');
  const originalText = btn.textContent;
  btn.disabled = true;
  btn.textContent = 'Processing...';

  try {
    const response = await fetch(`${API_BASE}/orders/create_order/`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
      },
      body: JSON.stringify({
        address_id: selectedAddressId,
        customer_note: document.getElementById('customer-note').value || ''
      })
    });

    const data = await response.json();

    if (response.ok) {
      // 订单创建成功 - 显示自定义弹窗
      showSuccessModal(data.order_number);
    } else {
      // 处理错误信息
      let errorMessage = 'Failed to place order';

      // 检查是否是库存不足错误
      if (data.stock_error) {
        errorMessage = data.stock_error;

        // 如果有详细的库存信息，添加到错误消息中
        if (data.details && Array.isArray(data.details)) {
          errorMessage += '\n\n' + data.details.join('\n');
        }
      } else if (data.error) {
        errorMessage = data.error;
      } else if (typeof data === 'string') {
        errorMessage = data;
      } else if (data.detail) {
        errorMessage = data.detail;
      }

      // 显示错误弹窗
      showErrorModal(errorMessage);

      btn.disabled = false;
      btn.textContent = originalText;
    }
  } catch (error) {
    console.error('Error placing order:', error);
    showErrorModal('Failed to place order. Please try again.');
    btn.disabled = false;
    btn.textContent = originalText;
  }
}

// 页面加载时执行
// Wait a bit to ensure user-auth.js has initialized global variables
document.addEventListener('DOMContentLoaded', () => {
  // Small delay to ensure global variables are initialized
  setTimeout(() => {
    loadCheckoutData();
  }, 100);
});
</script>
{% endblock %}
